﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Json;

namespace Zeus.Mvc.Infrastructure.Model
{
    [DataContract]
    [Serializable]
    public abstract class BaseResponse<T>
    {
        /// <summary>
        /// 成功是否
        /// </summary>
        [DataMember]
        public ResponseStatus Status { get; set; }

        /// <summary>
        /// 异常与否
        /// </summary>
        [DataMember]
        public string Message { get; set; }

        /// <summary>
        /// return single data
        /// </summary>
        [DataMember]
        public T Data { get; set; }

        /// <summary>
        /// return list data
        /// </summary>
        [DataMember]
        public List<T> ListData { get; set; }

        public override string ToString()
        {
            return string.Format("Status:{0}\nMessage:{1}\n", Status, Message);
        }
        /// <summary>
        /// 对象转为字符串
        /// </summary>
        /// <typeparam name="U"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson<U>(U obj)
        {
            DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(U));
            MemoryStream ms = new MemoryStream();
            ds.WriteObject(ms, obj);
            string strJSON = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return strJSON;
        }
        /// <summary>
        /// json数据转换对象 
        /// </summary>
        /// <typeparam name="U"></typeparam>
        /// <param name="sJson"></param>
        /// <returns></returns>
        public static U Deserialize<U>(string sJson) where U : struct
        {
            DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(U));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(sJson));
            U obj = (U)ds.ReadObject(ms);
            ms.Close();
            return obj;
        } 
    }
}
